package org.yefei.homeworkday30.two;

import java.io.*;
import java.util.*;
import org.dom4j.*;
import org.dom4j.io.*;

public class ReadXml {
	/*
	 * 二：products.xml基本信息解释如下： product为商品信息节点，discount表示是否折扣，如果是折扣商品，打七折；
	 * factoryaddr是工厂地址； itemno为商品编号，name为商品名称，price为商品单价，unit是计价单位，stockcount是库存量。
	 * 1：读取products.xml中的商品信息，输出。 2：查找商品信息：根据输入的商品号，输出对应的商品信息。
	 * 3：修改products.xml，输入商品编号（itemno）和数量，修改对应商品的数量（stockcount）；没有找到商品号，给出提示。
	 */
	// 1、读取products.xml中的商品信息，输出。

	public static void readXml() {
		try {
			SAXReader reader = new SAXReader();
//			Document doc = reader.read("src/org/yefei/homeworkday30/two/products.xml");
			Document doc = reader.read(
					ReadXml.class.getClassLoader().getResourceAsStream("org/yefei/homeworkday30/two/products.xml"));
			Element root = doc.getRootElement();
			// System.out.println("根节点的名称是：" + root.getName());
			@SuppressWarnings("unchecked")
			List<Element> list = root.selectNodes("product");
			for (Element e : list) {
				// 获得属性
				// 属性factoryadd：工厂地址；discount：表示是否折扣，如果是折扣商品，打七折
				String factoryadd = e.attributeValue("factoryaddr");
				String f = (factoryadd == null) ? "不详" : factoryadd;
				String discount = e.attributeValue("discount");
				Boolean dis = Boolean.parseBoolean(discount);
				String ss = dis == true ? "是" : "否";
				// 获取叶子节点
				// 叶子节点itemno：商品编号；name：商品名称；price：单价；stockcount：库存量；unit：单位
				String itemno = e.selectSingleNode("itemno").getText();
				int ite = Integer.parseInt(itemno);
				String n = e.selectSingleNode("name").getText();
				String price = e.selectSingleNode("price").getText();
				double p = Double.parseDouble(price);
				String stockcount = e.selectSingleNode("stockcount").getText();
				int st = Integer.parseInt(stockcount);
				String unit = e.selectSingleNode("unit").getText();
				System.out.println("工厂地址：" + f + "" + ",是否打七折：" + ss + ",商品编号：" + ite + ",商品名称：" + n + ",单价：" + p
						+ ",库存量：" + st + ",计价单位：" + unit);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 2：查找商品信息：根据输入的商品号，输出对应的商品信息。
	public static void search() throws Exception {
		SAXReader reader = new SAXReader();
		Document doc = reader.read("src/org/yefei/homeworkday30/two/products.xml");
		Element root = doc.getRootElement();
		@SuppressWarnings("unchecked")
		List<Element> list = root.selectNodes("product");
		Scanner in = new Scanner(System.in);
		System.out.println("请输入商品号：");
		while (true) {
			int bh = in.nextInt();
			for (Element e : list) {
				String itemno = e.selectSingleNode("itemno").getText();
				int ite = Integer.parseInt(itemno);
				String factoryadd = e.attributeValue("factoryaddr");
				String f = (factoryadd == null) ? "不详" : factoryadd;
				String discount = e.attributeValue("discount");
				Boolean dis = Boolean.parseBoolean(discount);
				String ss = dis == true ? "是" : "否";
				String n = e.selectSingleNode("name").getText();
				String price = e.selectSingleNode("price").getText();
				double p = Double.parseDouble(price);
				String stockcount = e.selectSingleNode("stockcount").getText();
				int st = Integer.parseInt(stockcount);
				String unit = e.selectSingleNode("unit").getText();
				if (bh == ite) {
					System.out.println("工厂地址：" + f + "" + ",是否打七折：" + ss + ",商品编号：" + ite + ",商品名称：" + n + ",单价：" + p
							+ ",库存量：" + st + ",计价单位：" + unit);
					return;
				} else
					continue;
			}
			System.out.println("该商品编号不存在，请重输：");
		}
	}

	// 3：修改products.xml，输入商品编号（itemno）和数量，修改对应商品的数量（stockcount）；没有找到商品号，给出提示。
	public static void modify() throws Exception {
		SAXReader reader = new SAXReader();
		Document doc = reader.read("src/org/yefei/homeworkday30/two/products.xml");
		Element root = doc.getRootElement();
		@SuppressWarnings("unchecked")
		List<Element> list = root.selectNodes("product");
		Scanner in = new Scanner(System.in);
		System.out.println("请输入商品号：");
		while (true) {
			int bh = in.nextInt();
			for (Element e : list) {
				String itemno = e.selectSingleNode("itemno").getText();
				int ite = Integer.parseInt(itemno);
				if (bh == ite) {
					System.out.println("请输入修改的数量：");
					String count = in.next();
					e.selectSingleNode("stockcount").setText(count);
					OutputFormat format = OutputFormat.createPrettyPrint();
					format.setEncoding("utf-8");
					XMLWriter xm = new XMLWriter(new FileWriter("src/org/yefei/homeworkday30/two/products.xml"),
							format);
					xm.write(doc);
					xm.close();
					System.out.println("修改成功！");
					return;
				} else
					continue;
			}
			System.out.println("该商品编号不存在，请重输：");
		}

	}

	// 4：以products.xml作为基础，实现客户购买的方法，输入商品号和购买数量，计算应付金额，如果是折扣商品，打七折；
	// 如果购买数量超过库存量，给出提示；商品不存在，给出提示；购买成功，扣除相应的数量。最后输出应付款的金额。
	public static double cal() throws Exception {
		double money = 0;
		SAXReader reader = new SAXReader();
		Document doc = reader.read("src/org/yefei/homeworkday30/two/products.xml");
		Element root = doc.getRootElement();
		@SuppressWarnings("unchecked")
		List<Element> list = root.selectNodes("product");
		Scanner in = new Scanner(System.in);
		System.out.println("请输入商品号：");
		while (true) {
			int bh = in.nextInt();
			for (Element e : list) {
				String itemno = e.selectSingleNode("itemno").getText();
				int ite = Integer.parseInt(itemno);
				String discount = e.attributeValue("discount");
				Boolean dis = Boolean.parseBoolean(discount);
				String price = e.selectSingleNode("price").getText();
				double p = Double.parseDouble(price);
				String stockcount = e.selectSingleNode("stockcount").getText();
				int st = Integer.parseInt(stockcount);
				if (bh == ite) {
					System.out.println("请输入购买数量：");
					while (true) {
						int count = in.nextInt();
						if (count <= st) {
							if (dis) {
								money = p * 0.7 * count;
								return money;
							} else {
								money = p * count;
								return money;
							}
						} else {
							System.out.println("库存不足，请重输：");
						}
					}
				} else
					continue;
			}
			System.out.println("该商品编号不存在，请重输：");
		}
	}

	// 5:增加新商品的功能，要求商品号和商品名称都不能重复（即不能和已经存在的重复）
	public static void addNewGoods() throws Exception {
		SAXReader reader = new SAXReader();
		Document doc = reader.read("src/org/yefei/homeworkday30/two/products.xml");
		Element root = doc.getRootElement();
		@SuppressWarnings("unchecked")
		List<Element> list = root.selectNodes("product");
		Scanner in = new Scanner(System.in);
		System.out.println("请输入商品号：");
		int bh = in.nextInt();
		System.out.println("请输入商品名称：");
		String gn = in.next();
		for (Element e : list) {
			String itemno = e.selectSingleNode("itemno").getText();
			int ite = Integer.parseInt(itemno);
			String n = e.selectSingleNode("name").getText();
			if (bh == ite && gn.equals(n)) {
				System.out.println("商品名和编号重复，无法添加！");
				return;
			} else
				continue;
		}
		System.out.println("该商品编号不存在，添加成功！");
		Element newGoods = root.addElement("product");
		newGoods.addAttribute("discount", "false");
		newGoods.addAttribute("factoryaddr", "上海");
		Element newItemno = newGoods.addElement("itemno");
		newItemno.setText(String.valueOf(bh));
		Element newName = newGoods.addElement("name");
		newName.setText(gn);
		Element newP = newGoods.addElement("price");
		newP.setText("66.9");
		Element newS = newGoods.addElement("stockcount");
		newS.setText("80");
		Element newU = newGoods.addElement("unit");
		newU.setText("瓶");
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("utf-8");
		XMLWriter xm = new XMLWriter(new FileWriter("src/org/yefei/homeworkday30/two/products.xml"), format);
		xm.write(doc);
		xm.close();
	}

	public static void main(String[] args) throws Exception {
		readXml();
		search();
		modify();
		System.out.println("库存充足，用户应付的金额是：" + cal());
		addNewGoods();
	}
}
